<template>
  <div class="tab-item" :class="{'tab-item-selected':data.selected}" ref="tabItemEl">
    <div class="label">{{ data.name }}</div>
    <i v-show="data.canClose"
       class="iconfont icon-close close"
       @click.prevent.stop="onClose">
    </i>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject, PropType, ref, watch } from 'vue';
import { ProvideKey, TabItem } from '@/ui-kit/tabs/index';

export default defineComponent({
  name: 'tab-item',
  emits: [],
  props: {
    data: {
      type: Object as PropType<TabItem>,
      required: true,
      default: () => {
        return { name: 'test' };
      },
    },
  },
  setup(props, { emit }) {
    const tabItemEl = ref();

    function scrollInView() {
      if (props.data.selected) {
        (tabItemEl.value as HTMLDivElement).scrollIntoView();
      }
    }

    watch(() => props.data, (val) => {
      scrollInView();
    });
    scrollInView();
    const closeCB = inject(ProvideKey.CloseTab, (data: TabItem) => {});
    return {
      tabItemEl,
      onClose() {
        closeCB(props.data);
      },
    };
  },
});
</script>
<style scoped lang="scss">
$color: black;
.tab-item {
  display: flex;
  flex-direction: row;
  border-radius: 5px 5px 0 0;
  margin: 0 3px;
  padding: 0 3px;
  border-top: solid 1px $color;
  border-left: solid 1px $color;
  border-right: solid 1px $color;
  align-items: center;
  justify-content: center;

  .label {
    flex: 1;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .close {
    cursor: pointer;
  }

  &-selected {
    background-color: #777777 !important;
  }

  &:hover {
    background-color: #999999;
  }
}

</style>
